package com.wanhugou.payment.util;

import java.util.Iterator;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.Map.Entry;

import com.wanhugou.payment.domain.PayLog;

public class ParamUtils {

	public static String getParam(PayLog pay){
		SortedMap<String, Object> map = new TreeMap<String, Object>();
		map.put("custId", pay.getCustId());
		map.put("payer", pay.getPayer());
		String resXml = getResXml(map);
		System.out.println("---------------"+resXml);
		return resXml;
	}
	
	public static PayLog returnParam(String xml) throws Exception{
		SortedMap<Object,Object> map = XMLUtil.doXMLParse(xml);
		PayLog pay = new PayLog();
		if (map.containsKey("custId")&&map.containsKey("payer")) {
			pay.setCustId(Integer.valueOf((String) map.get("custId")));
			pay.setPayer(Integer.valueOf((String) map.get("payer")));
		}
		System.out.println("------------------"+pay.toString());
		return pay;
	}
	

	/**
	 * @author wangkai
	 * @date
	 * @Description：将请求参数转换为xml格式的string
	 * @param parameters
	 *            请求参数
	 * @return
	 */
	public static String getResXml(SortedMap<String, Object> parameters) {
		StringBuffer sb = new StringBuffer();
		sb.append("<xml>");
		Iterator<Entry<String, Object>> iterator = parameters.entrySet().iterator();
		while (iterator.hasNext()) {
			Map.Entry<String,Object> entry = (Map.Entry<String,Object>) iterator.next();
			String key = (String) entry.getKey();
			Integer value = (Integer)entry.getValue();
			if ("attach".equalsIgnoreCase(key) || "body".equalsIgnoreCase(key)
					|| "sign".equalsIgnoreCase(key)) {
				sb.append("<" + key + ">" + "<![CDATA[" + value + "]]></" + key + ">");
			} else {
				sb.append("<" + key + ">" + value + "</" + key + ">");
			}
		}
		sb.append("</xml>");
		return sb.toString();
	}
	
}
